<?php


namespace app\sys\service;


use app\admin\controller\manage\Info;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\facade\Env;

class OfficeExe
{
    public static function getExcel($headArr, $dataArr)
    {

        $a = Env::get("app_path");
        $path = str_ireplace("application/", "", $a);
        $path = $path . "/download/card/";
        // 创建
        self::CreDir($path);
        // 删除文件
        self::delDirXlsx($path);

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        if (!$dataArr) {
            return "没有数据";
        }
        foreach ($headArr as $k => $v) {
            $sheet->setCellValueExplicitByColumnAndRow($k + 1, 1, $v, "s");
        }
        foreach ($dataArr as $k => $v) {
            $i = 0;
            foreach ($v as $v1 => $v2) {
                $i++;
                $sheet->setCellValueExplicitByColumnAndRow($i, $k + 2, $v2, "s");
            }
        }
        $te = $path . time() . '.xlsx';
        $writer = new Xlsx($spreadsheet);
        try {
            $writer->save($te);
        } catch (\PhpOffice\PhpSpreadsheet\Writer\Exception $e) {
            return "导出失败~";
        }
        return download($te);
    }

    public static function delDirXlsx($path)
    {
        if (is_dir($path)) {
            $arr = scandir($path);
            foreach ($arr as $k => $v) {
                $s = strpos($v, ".xlsx");
                if($s){
                    $strTime = mb_substr($v,0,$s);
                    $preDay = strtotime("-1 day");
                    if($strTime < $preDay){
                        unlink($path.$v);
                    }
                }
            }
        }
        return "";
    }

    public static function CreDir($path)
    {
        if(!is_dir($path)){
            if(mkdir($path,0777,true)) echo '目录创建成功！';
        }
    }
}